/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package IO.XML;



import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.*;
import org.xml.sax.SAXException;


public class XMLUtilities {
    
    private DocumentBuilderFactory factory;
    private DocumentBuilder docBuilder;
    private File xmlFile;
    private Document xmlDocument;
    private XMLReader xmlreader;
    public XMLUtilities(File xmlFile) {
        this.xmlFile = xmlFile;
    }
    
    public void Initialize() throws ParserConfigurationException {
        this.factory = DocumentBuilderFactory.newInstance();
        this.docBuilder = factory.newDocumentBuilder();
    }
    
    public void ParseFile() throws SAXException, IOException {
        this.xmlDocument = this.docBuilder.parse(this.xmlFile);
        this.xmlDocument.normalize();
    }
    
    public String GetRootName() {
        return this.xmlDocument.getDocumentElement().getNodeName();
    }
    
    public HashMap<String, String> GetConfiguration(String tagName, String[] properties) {
        HashMap<String, String> mapToReturn = new HashMap<String, String>(); 
        NodeList nodeLst = this.xmlDocument.getElementsByTagName(tagName);
        for (int s = 0; s < nodeLst.getLength(); s++) {
            Node fstNode = nodeLst.item(s);
            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                for(String property : properties) {
                    Element fstElmnt = (Element) fstNode;
                    NodeList list = fstElmnt.getElementsByTagName(property);
                    Element element = (Element) list.item(0);
                    NodeList fstNm = element.getChildNodes();
                    mapToReturn.put(property, ((Node) fstNm.item(0)).getNodeValue());
                }
               
            }
        }
        return mapToReturn;
    } 
    
    public List<Personaje> GetPersonajes() throws SAXException, ParserConfigurationException, IOException {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = saxParserFactory.newSAXParser();
        HandlerPersonaje handler = new HandlerPersonaje();
        saxParser.parse(this.xmlFile, handler);
        //Get Employees list
        List<Personaje> personajes = handler.getPersonajeList();
        return personajes;
    }
}
